package wang.controller;

import wang.bean.TouristAttraction;
import wang.dao.TouristAttractionDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@MultipartConfig
@WebServlet(name = "TouristAttractionController", value = "*.attraction")
public class TouristAttractionController extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();
    // 编写正则表达式，匹配以 / 开头，后面跟任意数量的任意字符（除了换行符），最后是 .attraction
    String regex = "/(\\w+)\\.attraction";
    // 编译正则表达式，创建Matcher对象
    String servletPath = request.getServletPath();
    Matcher matcher = Pattern.compile(regex).matcher(servletPath);
    if (!matcher.matches()) {
      return;
    }
    String requestUrl = matcher.group(1);
    TouristAttractionDao touristAttractionDao = new TouristAttractionDao();
    switch (requestUrl) {
      case "list": {
        String title = request.getParameter("title");
        String theme = request.getParameter("theme");
        List<TouristAttraction> touristAttractions = touristAttractionDao.list();
        if (title != null && !title.isEmpty()) {
          touristAttractions = touristAttractions.stream().filter(item -> title.equals(item.getTitle())).collect(Collectors.toList());
        }
        if (theme != null && !theme.isEmpty()) {
          touristAttractions = touristAttractions.stream().filter(item -> theme.equals(item.getTheme())).collect(Collectors.toList());
        }
        session.setAttribute("touristAttractions", touristAttractions);
        out.write("<script>location.href='admin_tourist_attraction.jsp';</script>");
        break;
      }
      case "update": {
        out.write("<script>alert('更新成功……');location.href='admin_tourist_attraction.jsp';</script>");
        break;
      }
      case "delete": {
        out.write("<script>alert('删除成功……');location.href='admin_tourist_attraction.jsp';</script>");
        break;
      }
    }
  }

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doGet(request, response);
  }
}
